<?php

namespace app\index\controller;

use think\Controller;
use think\Db;
use think\Session;

/**
 * 请求代理服务器获取微信用户信息
 */
class Wauth extends Controller
{
    protected $appid,$appsecret;

    // 是进来就去拿公众号的配置信息
    public function __construct()
    {
        $where['config'] = array('in','APPID,APPSECRET');
        $info = Db::name('web_config')
            ->where([ 'is_del' => '0'])
            ->where($where)
            ->field('config,value')
            ->select();
        foreach ($info as $k => $v){
            if('APPID' == $v['config']){
                $this -> appid = $v['value'];
            }
            if('APPSECRET'==$v['config']){
                $this -> appsecret = $v['value'];
            }
        }
    }


    /**
     * 微信授权
     */
    public function getRequest()
    {
        // 回调地址
        $redirecturl = urlencode("http://".$_SERVER['HTTP_HOST'].'/index/wauth/getInfo');

        // 微信接口地址
        $snsapi_userInfo_url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$this->appid.'&redirect_uri='.$redirecturl.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';

        // 请求接口
        header('Location:'.$snsapi_userInfo_url);
    }



    /**
     * 接收微信回调并处理数据
     */
    public function getInfo()
    {
        $code = $_GET['code'];
        if( isset($code) ){

            //1.通过code换取网页授权access_token
            $curl = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$this->appid.'&secret='.$this->appsecret.'&code='.$code.'&grant_type=authorization_code';
            $content = file_get_contents($curl);
            $result = json_decode($content,true);

            //2.通过access_token和openid拉取用户信息
            $webAccess_token = $result['access_token'];
            $openid = $result['openid'];
            $userInfourl = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$webAccess_token.'&openid='.$openid.'&lang=zh_CN ';

            // 3.获取信息
            $recontent = file_get_contents($userInfourl);

            // 4.用户信息
            $userInfo = json_decode($recontent,true);

            // 验证用户是否存在
            $u_info = Db::name('users')->where('openid',$userInfo['openid'])->find();

            // 用户已存在
            if(!empty($u_info) && isset($u_info)){
                // 写入缓存
                Session::set('uid',         $u_info['id']);                //用户id缓存
                Session::set('photo',       $u_info['photo']);             //用户头像
                Session::set('username',    $u_info['nickname']);          //用户姓名


                $this->uid          = $u_info['id'];
                $this->username     = $u_info['nickname'];
                $this->photo        = $u_info['photo'];


            // 用户首次访问
            } else {
                $params['nickname']     = $userInfo['nickname'];          // 微信昵称
                $params['openid']       = $userInfo['openid'];            // openid
                $params['photo']        = $userInfo['headimgurl'];        // 头像
                $params['sex']          = $userInfo['sex'];               // 性别 1男士 2女士
                $params['create_time']  = time();
                $params['update_time']  = time();

                $in_id = Db::name('users')->insertGetId($params);

                Session::set('uid',$in_id);
                Session::set('photo',$params['photo']);
                Session::set('username',$params['nickname']);

                $this->uid          = $in_id;
                $this->username     = $params['nickname'];
                $this->photo        = $params['photo'];

            }
            // 跳转到首页
            header('Location:'.url('gupiao.index/index'));

        } else {

            // 重新获取用户信息
            header('Location:'.url('getRequest'));
        }
    }


    /**
     * 模拟登陆
     * @return [type] [description]
     */
    public function login()
    {
        Session::set('openid','oTyhl0dMoEWMWeyO9j0gJ1ZPKkg4');
        Session::set('uid',1);
        $this->success('模拟登陆成功~',url('index/index/index'));
    }


    /**
     * 退出
     */
    public function loginOut()
    {
        Session(null);

        $this->success('已退出~',url('index/gupiao.index/index'));
    }



}
